package com.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.dao.UserDao;
import com.service.UserService;
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	public UserDao userDao;
	@Autowired
	private ApplicationContext applicationContext;
	@Override
	@Transactional(rollbackFor=Exception.class) 
	public int addUser(String name,Integer age) throws Exception{
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	paramMap.put("name", name);
    	paramMap.put("age", age);
		int result = userDao.addUser(paramMap);
		//测试事务
    	if(age==-1)
    		throw new Exception();//抛出异常则回滚
    	return result;
	}

	//手动控制事务提交、回滚
	@Override
	public int addUserWithManualTransactional(String name, Integer age) {
		int result = 0;
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	paramMap.put("name", name);
    	paramMap.put("age", age);
    	/*
    	 * 还有另一种获取DataSourceTransactionManager实例的方式，利用注解注入：
    	 *     @Autowired
    	 *     private DataSourceTransactionManager transactionManager;
    	 *     该bean在applicationContext.xml中有配置
    	 */
		DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) applicationContext.getBean("transactionManager");
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务，这样会比较安全些。
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
		try {
			result = userDao.addUser(paramMap);
	    	if(age==-1)
	    		throw new Exception();
	    	transactionManager.commit(status);
		} catch (Exception e) {
			transactionManager.rollback(status);
			result = 0;
		}
    	return result;
	}
	
	
	
	
	
	
	
}
